import * as types from "../types/addressListTypes";
import NetWorkUtil from "../utils/NetWorkUtil";
import ApiConstants from "../common/ApiConstants";
import { toastShort } from "../utils/ToastUtils";

export function getAddressList() {
  return dispatch => {
    dispatch({ type: types.ADDRESSLIST_INITING });
    NetWorkUtil.post(ApiConstants.ADDRESSLIST, {})
      .then(res => {
        dispatch({ type: types.ADDRESSLIST_DONE, addressList: res.list });
      })
      .catch(error => {
        dispatch({ type: types.ADDRESSLIST_ERROR, error });
      });
  };
}

export function deleteAddress(delivery_address_id) {
  return dispatch => {
    dispatch({ type: types.ADDRESSLIST_LOADING });
    NetWorkUtil.post(ApiConstants.DELETE_ADDRESS, { delivery_address_id })
      .then(res => {
        toastShort("地址删除成功");
        dispatch(getAddressList());
        dispatch({ type: types.ADDRESSLIST_DELETE_SUCCESS });
      })
      .catch(error => {
        toastShort("地址删除成功");
        dispatch({ type: types.ADDRESSLIST_DELETE_FAILED, error });
      });
  };
}

export function setDefaultAddress(delivery_address_id, callback) {
  return dispatch => {
    dispatch({ type: types.ADDRESSLIST_LOADING });
    NetWorkUtil.post(ApiConstants.SET_DEFAULT_ADDRESS, { delivery_address_id })
      .then(res => {
        toastShort("默认地址设置成功");
        dispatch(getAddressList());
        dispatch({ type: types.ADDRESSLIST_SETDEFAULT_SUCCESS });
        if (callback) {
          callback();
        }
      })
      .catch(error => {
        toastShort("默认地址设置失败");
        dispatch({ type: types.ADDRESSLIST_SETDEFAULT_FAILED, error });
      });
  };
}

export function unmount() {
  return dispatch => {
    dispatch({ type: types.ADDRESSLIST_UNMOUNT });
  };
}
